package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.Invoice;
import cn.itcast.domain.cargo.InvoiceExample;
import cn.itcast.service.cargo.InvoiceService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.BeanMapUtils;
import cn.itcast.web.utils.InvoiceNo;
import cn.itcast.web.utils.OssUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.*;
import org.aspectj.weaver.BCException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/invoice")
public class InvoiceController extends BaseController {


    @Reference
    private InvoiceService invoiceService;
    @Autowired
    private OssUtils ossUtils;


    /**
     * 计算各种值 封装然后返回到添加页面
     * @param id
     * @return
     */
    @RequestMapping("/toInvoice")
    public String toInvoice(String id) {
        Invoice invoice = invoiceService.toAdd(id);
        request.setAttribute("invoice",invoice);
        return "/cargo/invoice/invoice-add";
    }

    @RequestMapping("/list")
    public String list(
            @RequestParam(defaultValue = "1")Integer pageNum,
            @RequestParam(defaultValue = "5")Integer pageSize
    ) {
        InvoiceExample invoiceExample = new InvoiceExample();
        invoiceExample.createCriteria().andCompanyIdEqualTo(getLoginCompanyId());
        PageInfo<Invoice> pageInfo = invoiceService.findAllByPage(invoiceExample, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "/cargo/invoice/invoice-list";
    }

    @RequestMapping("/save")
    public String save(Invoice invoice, MultipartFile photo) {
        //保存基本信息
        invoice.setCompanyId(getLoginCompanyId());
        invoice.setCompanyName(getLoginCompanyName());
        invoice.setCreateBy(getLoginUser().getUserName());
        invoice.setCreateTime(new Date());
        invoice.setCreateDept(getLoginUser().getDeptName());
        //发票人
        invoice.setBlNo(getLoginUser().getUserName());
        //判断文件是否有
        if (!StringUtils.isEmpty(photo.getOriginalFilename())) {
            try {
                ossUtils.upload(photo.getInputStream(), "first_" + UUID.randomUUID().toString() + "." + Objects.requireNonNull(photo.getOriginalFilename()).split("\\.")[1]);
                String url = ossUtils.getUrl();
                invoice.setPickupPhoto(url);
            }catch (Exception e) {
                System.out.println(e.fillInStackTrace());
            }
        }
        invoice.setInvoiceNo(InvoiceNo.getInstance().GenerateOrder());
        //提单编号
        invoice.setBlNo(InvoiceNo.getInstance().GenerateOrder());
        invoiceService.save(invoice);
        return "redirect:/cargo/invoice/list";
    }

    @RequestMapping("/view")
    public String toView(String id) {
        Invoice invoice = invoiceService.selectByPrimaryKey(id);
        request.setAttribute("invoice",invoice);
        return "/cargo/invoice/invoice-view";
    }

    @RequestMapping("/safeToDelete")
    @ResponseBody
    public Map<String,Boolean> safeToDelete(String id) {
        return invoiceService.safeToDelete(id);
    }

    @RequestMapping("/delete")
    public String delete(String id) {
        invoiceService.delete(id);
        return "redirect:/cargo/invoice/list";
    }

    /**
     * 生成PDF
     * @param id
     * @return
     */
    @RequestMapping("/printPDF")
    public void printPdf(String id) throws IOException, JRException {
        Invoice invoice = invoiceService.selectByPrimaryKey(id);
        //获取pdf模板
        InputStream in = session.getServletContext().getResourceAsStream("/jasper/invoice.jasper");
        Map<String, Object> invoiceMap = BeanMapUtils.beanToMap(invoice);
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in,invoiceMap,new JREmptyDataSource());
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-disposition","attachment;fileName=export.pdf");
        ServletOutputStream out = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, out);
        out.close();
    }

}
